package edu.upc.fib.lamsandroid.server.lams.manager;

import edu.upc.fib.lamsandroid.server.api.model.*;
import edu.upc.fib.lamsandroid.server.lams.mapper.*;
import edu.upc.fib.lamsandroid.server.lams.model.*;
import edu.upc.fib.lamsandroid.server.manager.ActivityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ActivityManagerImpl implements ActivityManager {

    @Autowired
    private LamsLearningActivityMapper activityMapper;

    @Autowired
    private LamsToolMapper toolMapper;

    @Autowired
    private LamsToolContentMapper toolContentMapper;

    @Autowired
    private TlLanb11ContentMapper nbContentMapper;

    @Autowired
    private TlLarsrc11ResourceMapper srResourceMapper;

    @Autowired
    private TlLarsrc11ResourceItemMapper srResourceItemMapper;

    @Autowired
    private TlLarsrc11ItemInstructionMapper srResourceItemInstructionMapper;

    @Autowired
    private TlLaimag10ImagegalleryMapper imageGalleryMapper;

    @Autowired
    private TlLaimag10ImagegalleryItemMapper imageGalleryItemMapper;

    @Autowired
    private TlLaasse10AssessmentMapper assessmentMapper;

    @Autowired
    private TlLaasse10AssessmentQuestionMapper assessmentQuestionMapper;

    @Autowired
    private TlLaasse10QuestionOptionMapper assessmentOptionMapper;


    @Override
    public Activity fetchById(Long id) {

        LamsLearningActivityExample activityExample = new LamsLearningActivityExample();
        activityExample.createCriteria().andActivityIdEqualTo(id);
        List<LamsLearningActivityWithBLOBs> activities = activityMapper.selectByExampleWithBLOBs(activityExample);
        if(activities.size() > 0) {
            LamsLearningActivityWithBLOBs lamsActivity = activities.get(0);
            Activity activity = buildActivity(lamsActivity);
            addToolContent(activity, lamsActivity);
            return activity;
        }

        return null;
    }

    @Override
    public List<Activity> fetchAll() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    private Activity buildActivity(LamsLearningActivityWithBLOBs lamsActivity) {
        ToolType toolType = new ToolType();
        toolType.setExternalId(-1L);
        toolType.setName("unknown");
        toolType.setDescription("unknown tool, check logs");

        if(lamsActivity.getToolId() != null) {
            LamsToolExample toolExample = new LamsToolExample();
            toolExample.createCriteria().andToolIdEqualTo(lamsActivity.getToolId());
            List<LamsToolWithBLOBs> tools = toolMapper.selectByExampleWithBLOBs(toolExample);
            if(tools.size() > 0) {
                toolType.setExternalId(tools.get(0).getToolId());
                toolType.setName(tools.get(0).getToolDisplayName());
                toolType.setDescription(tools.get(0).getDescription());
            } else {
                System.out.println("Unknown TOOL!!");
            }
        } else {
            System.out.println("Activity without TOOL ASSOCIATED!!");
        }

        Activity activity = new Activity();
        activity.setToolType(toolType);
        activity.setExternalId(lamsActivity.getActivityId());
        activity.setCategoryId(lamsActivity.getActivityCategoryId());
        activity.setTypeId(lamsActivity.getLearningActivityTypeId());
        activity.setTitle(lamsActivity.getTitle());
        activity.setDescription(lamsActivity.getDescription());
        activity.setHelpText(lamsActivity.getHelpText());
        activity.setUiImage(lamsActivity.getLibraryActivityUiImage());

        return activity;
    }

    private void addToolContent(Activity activity, LamsLearningActivityWithBLOBs lamsActivity) {
        switch(activity.getToolType().getExternalId().intValue()) {
            case ToolType.NOTICEBOARDX: addNoticeboardContent(activity, lamsActivity); break;
            case ToolType.SHARED_RESOURCES: addSharedResourcesContent(activity, lamsActivity); break;
            case ToolType.IMAGE_GALLERY: addImageGalleryContent(activity, lamsActivity); break;
            case ToolType.ASSESSMENT: addAssessmentContent(activity, lamsActivity); break;

            case ToolType.FORUM:
            case ToolType.QUESTION_AND_ANSWER:
            case ToolType.SUBMIT_FILE:
            case ToolType.CHAT:
            case ToolType.VOTING:
            case ToolType.NOTEBOOK:
            case ToolType.SURVEY:
            case ToolType.SCRIBE:
            case ToolType.SHARED_TASKLIST:
            case ToolType.GMAP:
            case ToolType.SPREADSHEET:
            case ToolType.DATA_COLLECTION:
            case ToolType.WIKI:
            case ToolType.VIDEO_RECORDER:
            case ToolType.MINDMAP:
            case ToolType.PIXLR:
            case ToolType.EADVENTURE:
            case ToolType.WOOKIE:
            case ToolType.SHARED_COMMON_CARTRIDGE:
            case ToolType.BBB:
            case ToolType.MCQ:
            case ToolType.DIMDIM:
                System.out.println("Tool type still not managed: " + activity.getToolType().getName());
                break;
            default:
                System.out.println("Unknown tool type at addToolContent() !!");

        }
    }

    private void addNoticeboardContent(Activity activity, LamsLearningActivityWithBLOBs lamsActivity) {
        LamsToolContentExample toolContentExample = new LamsToolContentExample();
        toolContentExample.createCriteria().andToolContentIdEqualTo(lamsActivity.getToolContentId());
        List<LamsToolContent> toolContents = toolContentMapper.selectByExample(toolContentExample);
        if(toolContents.size() > 0) {
            TlLanb11ContentExample nbContentExample = new TlLanb11ContentExample();
            nbContentExample.createCriteria().andNbContentIdEqualTo(toolContents.get(0).getToolContentId());
            List<TlLanb11ContentWithBLOBs> nbContents = nbContentMapper.selectByExampleWithBLOBs(nbContentExample);
            if(nbContents.size() > 0) {
                ToolContent toolContent = new ToolContent();
                toolContent.setExternalId(nbContents.get(0).getUid());
                toolContent.setData(new ToolContentDataNoticeBoard(nbContents.get(0).getContent()));
                activity.setToolContent(toolContent);
            } else {
                System.out.println("Noticeboard content NOT FOUND!!");
            }
        } else {
            System.out.println("Cannot find tool content!!");
        }
    }

    private void addSharedResourcesContent(Activity activity, LamsLearningActivityWithBLOBs lamsActivity) {
        LamsToolContentExample toolContentExample = new LamsToolContentExample();
        toolContentExample.createCriteria().andToolContentIdEqualTo(lamsActivity.getToolContentId());
        List<LamsToolContent> toolContents = toolContentMapper.selectByExample(toolContentExample);
        if(toolContents.size() > 0) {
            TlLarsrc11ResourceExample srResourceExample = new TlLarsrc11ResourceExample();
            srResourceExample.createCriteria().andContentIdEqualTo(toolContents.get(0).getToolContentId());
            List<TlLarsrc11ResourceWithBLOBs> srResources = srResourceMapper.selectByExampleWithBLOBs(srResourceExample);
            if(srResources.size() > 0) {
                System.out.println("Found "+srResources.size() + " SharedResources resources");

                // shared resource main attributes
                ToolContentDataSharedResources data = new ToolContentDataSharedResources(
                        srResources.get(0).getTitle(), srResources.get(0).getInstructions());


                // items
                ArrayList<ToolContentDataSharedResourcesItem> items = new ArrayList<ToolContentDataSharedResourcesItem>();

                TlLarsrc11ResourceItemExample srResourceItemExample = new TlLarsrc11ResourceItemExample();
                srResourceItemExample.createCriteria().andResourceUidEqualTo(srResources.get(0).getUid());
                srResourceItemExample.setOrderByClause("uid ASC");
                List<TlLarsrc11ResourceItemWithBLOBs> srResourceItems = srResourceItemMapper.selectByExampleWithBLOBs(srResourceItemExample);
                if(srResourceItems.size() > 0) {
                    System.out.println("Found " + srResourceItems.size() + " resource items");

                    for(TlLarsrc11ResourceItemWithBLOBs resourceItem : srResourceItems) {

                        // item main attributes
                        ToolContentDataSharedResourcesItem item = new ToolContentDataSharedResourcesItem(
                                resourceItem.getFileUuid(), resourceItem.getTitle(), resourceItem.getUrl(),
                                resourceItem.getFileType(), resourceItem.getFileName());

                        // and item instructions
                        ArrayList<String> instructions = new ArrayList<String>();

                        TlLarsrc11ItemInstructionExample itemInstructionExample = new TlLarsrc11ItemInstructionExample();
                        itemInstructionExample.createCriteria().andItemUidEqualTo(resourceItem.getUid());
                        itemInstructionExample.setOrderByClause("sequence_id ASC");
                        List<TlLarsrc11ItemInstruction> srInstructions =  srResourceItemInstructionMapper.selectByExample(itemInstructionExample);
                        if(srInstructions.size() > 0) {
                            System.out.println("Found " + srInstructions.size() + " resource item instructions");
                            for(TlLarsrc11ItemInstruction srIntruction : srInstructions) {
                                instructions.add(srIntruction.getDescription());
                            }
                        }
                        item.setInstructions(instructions);

                        items.add(item);
                    }
                }

                data.setItems(items);

                ToolContent toolContent = new ToolContent();
                toolContent.setExternalId(srResources.get(0).getUid());
                toolContent.setData(data);
                activity.setToolContent(toolContent);
            } else {
                System.out.println("SharedResources resources NOT FOUND!!");
            }
        } else {
            System.out.println("Cannot find tool content!!");
        }
    }


    private void addImageGalleryContent(Activity activity, LamsLearningActivityWithBLOBs lamsActivity) {
        LamsToolContentExample toolContentExample = new LamsToolContentExample();
        toolContentExample.createCriteria().andToolContentIdEqualTo(lamsActivity.getToolContentId());
        List<LamsToolContent> toolContents = toolContentMapper.selectByExample(toolContentExample);
        if(toolContents.size() > 0) {
            TlLaimag10ImagegalleryExample imageGalleryExample = new TlLaimag10ImagegalleryExample();
            imageGalleryExample.createCriteria().andContentIdEqualTo(toolContents.get(0).getToolContentId());
            List<TlLaimag10ImagegalleryWithBLOBs> imageGalleries = imageGalleryMapper.selectByExampleWithBLOBs(imageGalleryExample);
            if(imageGalleries.size() > 0) {

                // image gallery main attributes
                ToolContentDataImageGallery data = new ToolContentDataImageGallery(imageGalleries.get(0).getInstructions());

                // items
                ArrayList<ToolContentDataImageGalleryItem> items = new ArrayList<ToolContentDataImageGalleryItem>();

                TlLaimag10ImagegalleryItemExample imageGalleryItemExample = new TlLaimag10ImagegalleryItemExample();
                imageGalleryItemExample.createCriteria().andImagegalleryUidEqualTo(imageGalleries.get(0).getUid());
                List<TlLaimag10ImagegalleryItem> imageGalleryItems = imageGalleryItemMapper.selectByExample(imageGalleryItemExample);
                if(imageGalleryItems.size() > 0) {
                    System.out.println("Found " + imageGalleryItems.size() + " image gallery items");

                    for(TlLaimag10ImagegalleryItem imageGalleryItem : imageGalleryItems) {
                        ToolContentDataImageGalleryItem item = new ToolContentDataImageGalleryItem(
                                imageGalleryItem.getTitle(), imageGalleryItem.getDescription(),
                                imageGalleryItem.getOriginalFileUuid(), imageGalleryItem.getMediumFileUuid(),
                                imageGalleryItem.getThumbnailFileUuid(), imageGalleryItem.getFileType(),
                                imageGalleryItem.getFileName());

                        items.add(item);
                    }
                }

                data.setItems(items);

                ToolContent toolContent = new ToolContent();
                toolContent.setExternalId(imageGalleries.get(0).getUid());
                toolContent.setData(data);
                activity.setToolContent(toolContent);
            } else {
                System.out.println("image gallery content NOT FOUND!!");
            }
        } else {
            System.out.println("Cannot find tool content!!");
        }
    }

    private void addAssessmentContent(Activity activity, LamsLearningActivityWithBLOBs lamsActivity) {
        LamsToolContentExample toolContentExample = new LamsToolContentExample();
        toolContentExample.createCriteria().andToolContentIdEqualTo(lamsActivity.getToolContentId());
        List<LamsToolContent> toolContents = toolContentMapper.selectByExample(toolContentExample);
        if(toolContents.size() > 0) {
            TlLaasse10AssessmentExample assessmentExample = new TlLaasse10AssessmentExample();
            assessmentExample.createCriteria().andContentIdEqualTo(toolContents.get(0).getToolContentId());
            List<TlLaasse10AssessmentWithBLOBs> assessment = assessmentMapper.selectByExampleWithBLOBs(assessmentExample);
            if(assessment.size() > 0) {
                // assessment main attributes
                ToolContentDataAssessment data = new ToolContentDataAssessment();
                data.setTitle(assessment.get(0).getTitle());
                data.setInstructions(assessment.get(0).getInstructions());

                // questions
                ArrayList<ToolContentDataAssessmentQuestion> questions = new ArrayList<ToolContentDataAssessmentQuestion>();

                TlLaasse10AssessmentQuestionExample questionExample = new TlLaasse10AssessmentQuestionExample();
                questionExample.createCriteria().andAssessmentUidEqualTo(assessment.get(0).getUid());
                List<TlLaasse10AssessmentQuestionWithBLOBs> lamsQuestions = assessmentQuestionMapper.selectByExampleWithBLOBs(questionExample);
                if(lamsQuestions.size() > 0) {
                    System.out.println("Found " + lamsQuestions.size() + " assessment questions");

                    for (TlLaasse10AssessmentQuestionWithBLOBs lamsQuestion : lamsQuestions) {
                        // question main attributes
                        ToolContentDataAssessmentQuestion question = new ToolContentDataAssessmentQuestion();
                        question.setTitle(lamsQuestion.getTitle());
                        question.setBody(lamsQuestion.getQuestion());
                        question.setTrueFalseCorrectAnswer(lamsQuestion.getCorrectAnswer() == 1);
                        question.setType(lamsQuestion.getQuestionType());

                        // options
                        ArrayList<ToolContentDataAssessmentQuestionOption> options = new ArrayList<ToolContentDataAssessmentQuestionOption>();

                        TlLaasse10QuestionOptionExample optionExample = new TlLaasse10QuestionOptionExample();
                        optionExample.createCriteria().andQuestionUidEqualTo(lamsQuestion.getUid());
                        List<TlLaasse10QuestionOptionWithBLOBs> lamsOptions = assessmentOptionMapper.selectByExampleWithBLOBs(optionExample);

                        for (TlLaasse10QuestionOptionWithBLOBs lamsOption : lamsOptions) {
                            ToolContentDataAssessmentQuestionOption option = new ToolContentDataAssessmentQuestionOption();
                            option.setSpecificQuestion(lamsOption.getQuestion());
                            option.setFloatValue(lamsOption.getOptionFloat());
                            option.setOrderIndex(lamsOption.getSequenceId());
                            option.setStringValue(lamsOption.getOptionString());

                            options.add(option);
                        }
                        question.setOptions(options);

                        questions.add(question);
                    }

                    data.setQuestions(questions);
                }

                ToolContent toolContent = new ToolContent();
                toolContent.setExternalId(assessment.get(0).getUid());
                toolContent.setData(data);
                activity.setToolContent(toolContent);
            }
        }
    }
}